import os
import json
import logging
from pathlib import Path
from sqlalchemy import delete
from app.services.db import SessionLocal
from app.models.stock_dict import StockDict

def get_stock_detail(region: str, code: str) -> dict:
    try:
        region_u = str(region).upper()
        code_u = str(code).upper()
        if region_u in {"SH", "SZ"}:
            p = Path("app/static/stocks_cn.json")
            if p.exists():
                m = json.loads(p.read_text(encoding="utf-8"))
                name = m.get(code_u[:6]) or m.get(code_u)
                d = {"c": code_u, "n": name or "", "e": "SH" if region_u == "SH" else "SZ"}
                return {"code": 0, "msg": "ok", "data": d}
        if region_u == "HK":
            p = Path("app/static/stocks_hk.json")
            if p.exists():
                m = json.loads(p.read_text(encoding="utf-8"))
                name = m.get(code_u) or m.get(code_u.lstrip("0"))
                d = {"c": code_u, "n": name or "", "e": "HKEX"}
                return {"code": 0, "msg": "ok", "data": d}
        return {"code": 0, "msg": "ok", "data": {"c": code_u, "n": "", "e": region_u}}
    except Exception as e:
        try:
            logging.error(json.dumps({"event": "stock_detail_local_error", "region": region, "code": code, "error": str(e)}, ensure_ascii=False))
        except Exception:
            pass
        return {"code": -1, "msg": "local lookup failed", "data": {}}

def update_cn_names_mairui_db() -> int:
    import requests
    try:
        url = os.getenv("MAIRUI_HSLT_URL", "https://api.mairui.club/hslt/list/b997d4403688d5e66a")
        r = requests.get(url, timeout=20)
        arr = r.json() if r.status_code == 200 else []
        s = SessionLocal()
        try:
            s.execute(delete(StockDict))
            s.commit()
            items = []
            for x in arr:
                dm = str(x.get("dm") or "").strip()
                mc = str(x.get("mc") or "").strip()
                jys = str(x.get("jys") or "").strip().upper()
                if not dm or not mc:
                    continue
                k = dm.split(".")[0][:6]
                exch = jys if jys in {"SH","SZ"} else (dm.split(".")[-1].upper() if "." in dm else None)
                items.append(StockDict(code=k, name=mc, exchange=exch))
            if items:
                s.add_all(items)
                s.commit()
            logging.info(json.dumps({"event": "update_cn_names_mairui_db", "count": len(items)}, ensure_ascii=False))
            return len(items)
        finally:
            s.close()
    except Exception as e:
        logging.error(json.dumps({"event": "update_cn_names_mairui_db_error", "error": str(e)}, ensure_ascii=False))
        return 0
